package mmodel

import (
	"database/sql/driver"
	"fmt"
	"gitee.com/dennis-mxx/mxx-core-v2/mutil"
	"strings"
	"time"
)

type LocalDatetime time.Time

func (ce LocalDatetime) Value() (driver.Value, error) {
	return ce.Time(), nil
}
func (ce *LocalDatetime) Scan(src any) error {
	switch src.(type) {
	case time.Time:
		*ce = LocalDatetime(src.(time.Time))
		return nil
	case []uint8:
		s := String(src.(string))
		*ce = LocalDatetime((&s).Time())
		return nil
	}
	return fmt.Errorf("unsupported Scan, storing driver.Value type %T into type mmodel.LocalDatetime", src)

}
func (ce *LocalDatetime) UnmarshalJSON(data []byte) (err error) {
	defer func() {
		er := recover()
		if er != nil {
			err = er.(error)
		}
	}()
	str := ReadString(data)
	*ce = LocalDatetime(str.Time())
	return nil
}

func (ce *LocalDatetime) MarshalJSON() ([]byte, error) {
	if ce.IsNull() {
		return []byte("\"\""), nil
	}
	str := ce.String()
	if strings.HasSuffix(str, "00:00:00") {
		return []byte(fmt.Sprintf("\"%s\"", str[0:10])), nil
	}
	return []byte(fmt.Sprintf("\"%s\"", str)), nil
}

func (ce LocalDatetime) String() string {
	return mutil.DateUtil.DateTimeToStr(time.Time(ce))
}

func (ce LocalDatetime) IsNull() bool {
	t := time.Time(ce)
	return t.Year() == 1 && t.Month() == 1 && t.Day() == 1
}

func (ce LocalDatetime) Time() time.Time {
	return time.Time(ce)
}
func NowLocalDateTime() *LocalDatetime {
	now := LocalDatetime(mutil.DateUtil.NowDateTime())
	return &now
}
func NowLocalDateTimeStr() String {
	now := LocalDatetime(mutil.DateUtil.NowDateTime())
	return String(now.String())
}
func ToLocalDateTime(str string) LocalDatetime {
	s := String(str)
	return s.LocalDateTime()
}
